import { defineStore } from 'pinia'
import { addDynamicRoutes, resetDynamicRoutes } from '@/router/utils'
// 用户信息 storageLocal key
export const UserKey = 'user-info'

export const useUserStore = defineStore('user', {
  state: (): UserInfo => {
    const localUser = localStorage.getItem(UserKey)
    let user = {
      id: null,
      avatar: '',
      username: '',
      nickname: '',
      roles: [],
      menus: [],
      permissions: []
    } as UserInfo
    if (localUser) {
      user = JSON.parse(localUser)
    }
    return user
  },
  actions: {
    SET_USER(user: UserInfo) {
      this.id = user.id
      this.avatar = user.avatar
      this.username = user.username
      this.nickname = user.nickname
      this.roles = user.roles
      this.menus = user.menus
      this.permissions = user.permissions
      localStorage.setItem(UserKey, JSON.stringify(this))
      addDynamicRoutes()
    },
    CLEAR_USER() {
      this.id = null
      this.avatar = ''
      this.username = ''
      this.nickname = ''
      this.roles = []
      this.menus = []
      this.permissions = []
      localStorage.removeItem(UserKey)
      resetDynamicRoutes()
    }
  }
})

export const getUser = (): UserInfo => {
  const userLocal = localStorage.getItem(UserKey)
  return userLocal ? JSON.parse(userLocal) : ({} as UserInfo)
}
